package ${packageName};

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class BaseDao<T> implements BaseMapper<T> {
	private SqlSession session;
	private Class<? extends BaseMapper<T>> type;

	protected void set(Class<? extends BaseMapper<T>> clazz) {
		this.type = clazz;
	}

	public BaseDao() {
		SqlSessionFactory sessionFactory;
		try {
			sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
			session = sessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public T getById(Serializable PK) {
		return session.getMapper(type).getById(PK);
	}

	public void save(T t) {
		session.getMapper(type).save(t);
		session.commit();

	}

	public void saveOrUpdate(T t) {
		session.getMapper(type).saveOrUpdate(t);
		session.commit();
	}

	public void removeById(Serializable id) {
		session.getMapper(type).removeById(id);
		session.commit();

	}

	public void remove(T t) {
		session.getMapper(type).remove(t);
		session.commit();
	}

	public void removeAll(Collection<T> ts) {
		if (ts != null && !ts.isEmpty()) {
			Iterator<T> i = ts.iterator();
			while (i.hasNext()) {
				session.getMapper(type).remove(i.next());
			}
			session.commit();
		}
	}

	public List<T> getAll() {
		return session.getMapper(type).getAll();
	}

	public int count(T t) {
		return session.getMapper(type).count(t);
	}

	public void saveBatch(Collection<T> ts) {
		if (ts != null && !ts.isEmpty()) {
			Iterator<T> i = ts.iterator();
			while (i.hasNext()) {
				session.getMapper(type).save(i.next());
			}
			session.commit();
		}
	}

}